package com.ruoyi.web.controller.common;

/**
 * @Author: Zhihj
 * @Date: 2023-03-29 22:12:51
 */

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 */
@RestController
public class CaptchaController {
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response){
        System.out.println("生成验证码功能被调用");
        AjaxResult ajax = AjaxResult.success();
        /**
         * boolean captchaEnabled = configService.selectCaptchaEnabled();
         *         ajax.put("captchaEnabled", captchaEnabled);
         *         if (!captchaEnabled)
         *         {
         *             return ajax;
         *         }
         */
        //保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY+ uuid;
        //capText: 1*2=@2
        String capText = captchaProducerMath.createText();
        String capStr = capText.substring(0, capText.lastIndexOf('@'));
        String capResult = capText.substring(capText.lastIndexOf('@')+1);
        BufferedImage image = captchaProducerMath.createImage(capStr);//生成图片


        //将验证码缓存道redis中
        redisTemplate.opsForValue().set(verifyKey,capResult,2, TimeUnit.MINUTES);

        //将图片传输到前台页面
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将图片和uuid传递给前台
        ajax.put("uuid",uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));

        return ajax;

    }

}
